<?php
View::tplInclude('Public/header');
?>
<script type="text/javascript">
window.UMEDITOR_HOME_URL = '/static/ueditor/';
</script>
<link href="/static/ueditor/themes/default/css/umeditor.min.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/static/ueditor/umeditor.config.js"></script>
<script type="text/javascript" src="/static/ueditor/umeditor.min.js"></script>
<script type="text/javascript" src="/static/swfupload/swfupload.js"></script>
<div class="container">
<div class='row'>
    <div class="span3 bs-docs-sidebar">
        <ul class="nav nav-list bs-docs-sidenav">
          <li><a href="#edit"><i class="icon-chevron-right"></i> 新增/编辑</a></li>
          <li><a href="#list"><i class="icon-chevron-right"></i> 列表</a></li>
        </ul>
    </div>
    <div class="span9">
        <h1>时间轴管理</h1>
        <section id="edit">
            <form class='form-horizontal' id='mainForm'>
                <input type='hidden' name='id' />
                <div class="control-group">
                    <label class="control-label">选择类型</label>
                    <div class="controls">
                        <select name='type'>
                            <option value='1'>普通</option>
                            <option value='2'>大事记</option>
                            <option value='3'>头条</option>
                        </select>
                        <span class="help-inline">头条只能有1个哦</span>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label">开始时间</label>
                    <div class="controls">
                        <div id="startDate" class="input-append">
                        <input name='startDate' data-format="yyyy-MM-dd hh:mm:ss" type="text" placeholder='必填哦' />
                        <span class="add-on">
                        <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
                        </span>
                        </div>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label">结束时间</label>
                    <div class="controls">
                        <div id="endDate" class="input-append">
                        <input name='endDate' data-format="yyyy-MM-dd hh:mm:ss" type="text" placeholder='可空' />
                        <span class="add-on">
                        <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
                        </span>
                        </div>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label">标题</label>
                    <div class="controls">
                        <input type="text" name='title' placeholder="必填哦" />
                        <span class="help-inline">不超过10个字</span>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label">多媒体内容</label>
                    <div class="controls">
                        <button class="btn btn-primary" type="button" data-toggle="modal" data-target="#asset">编辑</button>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label">文本内容</label>
                    <div class="controls">
                        <textarea name="text" id="myEditor"></textarea>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-primary" onclick='javascript:submitMain(1);'>写好啦</button>
                    <button type="button" class="btn btn-primary" onclick='javascript:submitMain(0);'>存草稿</button>
                    <button type="button" class="btn btn-danger" onclick='javascript:resetMain();'>重置</button>
                </div>
            </form>
        </section>
        <section id="list">
            <table class="table table-hover">
                <thead><tr><td>类型</td><td>开始时间</td><td>结束时间</td><td>标题</td><td>操作</td></tr></thead>
                <tbody>

                </tbody>
            </table>
            <div class="pagination">
                <ul>
                    <?php echo $page;?>
                </ul>
            </div>
        </section>
    </div>
</div>
</div>

<div id="asset" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="assetLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="assetLabel">编辑多媒体</h3>
    </div>
    <div class="modal-body">
        <form class='form-horizontal' id='assetForm'>
            <ul class="nav nav-tabs" id="myTab">
                <li class="active"><a href="#net">URL</a></li>
                <li><a href="#upload">上传</a></li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane active" id="net">
                    <div class="control-group">
                        <label class="control-label">URL</label>
                        <div class="controls">
                            <input type="text" id='url' name='url' placeholder="url路径" />
                            <span class="help-inline"></span>
                        </div>
                    </div>
                </div>
                <div class="tab-pane" id="upload">
                    <div class="control-group">
                        <label class="control-label">选择文件</label>
                        <div class="controls">
                            <span class="uploadbutton"><span id="spanButtonPlaceholder"></span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="control-group">
                <label class="control-label">标题</label>
                <div class="controls">
                    <input type="text" name='caption' placeholder="可空" />
                </div>
            </div>
            <div class="control-group">
                <label class="control-label">作者</label>
                <div class="controls">
                    <input type="text" name='credit' placeholder="可空" />
                </div>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">关闭</button>
        <button class="btn btn-primary" onclick='javascript:saveAsset();'>保存</button>
        <button class="btn btn-danger" onclick='javascript:delAsset();'>删除多媒体</button>
    </div>
</div>
<div id="beautyAlert" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="beautyLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="beautyLabel"></h3>
  </div>
  <div class="modal-body">
  </div>
  <div class="modal-footer">
  </div>
</div>
<script type="text/javascript">
window.timelineList = <?php echo $list;?>;
$(function() {
    genList(timelineList);
    $('#startDate').datetimepicker({
        language: 'en'
    });
    $('#endDate').datetimepicker({
        language: 'en'
    });
    $('#myTab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });
    $('#url').on('change blur',function(){
        if($('#url').val() == ''){
            $('#url').parent().parent().addClass('error');
            $('#url + span').text('URL不可空');
        }else{
            $('#url').parent().parent().removeClass('error');
            $('#url + span').text('');
        }
    });
    $('input[name=startDate]').on('change blur',function(){
        if($('input[name=startDate]').val() == ''){
            $('#startDate').parent().parent().addClass('error');
        }else{
            $('#startDate').parent().parent().removeClass('error');
        }
    });
    $('#mainForm select[name=type]').on('change',function(){
        var type = $('#mainForm select[name=type]').val();
        switch(type){
            case '1':
                $('#mainForm input[name=startDate]').parents('.control-group').show();
                $('#mainForm input[name=endDate]').parents('.control-group').show();
                $('#mainForm input[name=endDate]').prop('placeholder','可空');
                $('#myEditor').parents('.control-group').show();
                break;
            case '2':
                $('#mainForm input[name=startDate]').parents('.control-group').show();
                $('#mainForm input[name=endDate]').parents('.control-group').show();
                $('#mainForm input[name=endDate]').prop('placeholder','必填哦');
                $('#myEditor').parents('.control-group').hide();
                break;
            case '3':
                $('#mainForm input[name=startDate]').parents('.control-group').hide();
                $('#mainForm input[name=endDate]').parents('.control-group').hide();
                $('#myEditor').parents('.control-group').show();
                break;
        }
    });
    setTimeout(function () {
      $('.bs-docs-sidenav').affix({
        offset: {
          top : 0
        , bottom: 270
        }
      })
    }, 100);
    $(document).on('click','.pagination a',function(e){
        e.preventDefault();
        $("#list").mask("给力加载中...");
        rawUrl = $(this).prop('href');
        page = getUrlParam(rawUrl, 'p');
        $.get('/admin/index.php?m=Index&a=GetList', {p:page}, function(data){
            if(data.status !== true){
                alert('请求出错');
            }else{
                window.timelineList = data.data.list;
                genList(timelineList);
                $('.pagination ul').html(data.data.page);
            }
            $("#list").unmask();
        }, 'json');
    });
    $('#list').on('click','.del',function(){
        id = $(this).parents('tr').attr('id');
        window.delId = id.substr(3);
        option = {
            title:'确认删除？',
            content:'确认要删除该记录？',
            buttons:[
                {type:'close',text:'取消'},
                {text:'确定',click:function(){
                    page = $('.pagination .active').text();
                    $("#list").mask("给力加载中...");
                    $.post('/admin/index.php?m=Index&a=Del', {id:window.delId,p:page}, function(data){
                        if(data.status !== true){
                            alert('请求出错');
                        }else{
                            window.timelineList = data.data.list;
                            genList(timelineList);
                            $('.pagination ul').html(data.data.page);
                        }
                        $("#list").unmask();
                        $('#beautyAlert').modal('hide');
                    }, 'json');
                }}
            ]
        };
        beautyAlert(option);
    }).on('click','.edit',function(){
        id = $(this).parents('tr').attr('id').substr(3);
        offset = searchList(id);
        if(offset == -1){
            alert('记录不存在');
            return;
        }
        resetMain();
        data = window.timelineList[offset];
        $('#mainForm input[name=id]').val(id);
        $('#mainForm select[name=type]').val(data.type);
        $('#mainForm input[name=startDate]').val(data.startDate);
        $('#mainForm input[name=endDate]').val(data.endDate);
        $('#mainForm input[name=title]').val(data.headline);
        ue.setContent(htmlspecialchars_decode(data.text));
        $('#mainForm select[name=type]').trigger('change');
        if($.trim(data.asset) == ''){
            assetObj = {};
        }else{
            assetObj = $.parseJSON(data.asset);
        }
        window.asset = assetObj;
        $('#assetForm input[name=url]').val(assetObj.media);
        $('#assetForm input[name=caption]').val(assetObj.caption);
        $('#assetForm input[name=credit]').val(assetObj.credit);
        location.href = '#edit';
    }).on('click','.temp',function(){
        id = $(this).parents('tr').attr('id').substr(3);
        switchTemp(id, 0);
    }).on('click','.noTemp',function(){
        id = $(this).parents('tr').attr('id').substr(3);
        switchTemp(id, 1);
    });
    window.ue = UM.getEditor("myEditor");
    var settings = {
        file_post_name: 'upfile',
        upload_url: "/admin/index.php?c=Index&a=Upload&type=ajax",
        file_size_limit : "1 MB",
        file_types : "*.jpg;*.png;*.jpeg;*.gif",
        file_types_description : "JPG Images; PNG Image ; JPEG Images ;GIF Image ;",
        file_upload_limit : 0,
        file_queue_limit : 0,
        file_dialog_complete_handler : fileDialogComplete,
        upload_success_handler : uploadSuccess,
        button_image_url : "",
        button_placeholder_id : "spanButtonPlaceholder",
        button_width: 78,
        button_height: 36,
        button_text : '<span class="thumb"></span>',
        button_text_style : '.thumb { background: #BABABA; height: 36px; line-height: 36px; font-size: 16px; color: #FFF; padding: 0px 12px; cursor: pointer; display: inline-block; float: left; }',
        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
        button_cursor: SWFUpload.CURSOR.HAND,

        flash_url : "/static/swfupload/swfupload.swf",
        debug: false,
        post_params : {
            user:$.cookie('user'),
            auth:$.cookie('auth')
        }

    };
    var swfu = new SWFUpload(settings);
});
function fileDialogComplete(numFilesSelected, numFilesQueued) {
    this.startUpload();
}

function uploadSuccess(file, data) {
    $('#url').val(data);
    $('#myTab a:first').tab('show');
}
function beautyAlert(option){
    title = option.title;
    content = option.content;
    buttons = option.buttons;
    $('#beautyLabel').text(title);
    $('#beautyAlert .modal-body').html(content);
    var buttonHtml = '';
    for(var x in buttons){
        button = buttons[x];
        if(button.type == 'close'){
            buttonHtml += '<button class="btn" data-dismiss="modal" aria-hidden="true">'+button.text+'</button>';
        }else{
            buttonHtml += '<button class="btn btn-primary" id="beautyAlert_btn_'+x+'">'+button.text+'</button>';
            $('#beautyAlert').on('click', '#beautyAlert_btn_'+x, button.click);
        }
    }
    $('#beautyAlert .modal-footer').html(buttonHtml);
    $('#beautyAlert').modal();
}
function saveAsset(){
    if($('#url').val() == ''){
        $('#url').parent().parent().addClass('error');
        $('#url + span').text('URL不可空');
        return;
    }
    window.asset = {
        media:$('#assetForm input[name=url]').val(),
        caption:$('#assetForm input[name=caption]').val(),
        credit:$('#assetForm input[name=credit]').val()
    };
    $('#asset').modal('hide');
}
function delAsset(){
    $('#assetForm')[0].reset();
    window.asset = {};
    $('#asset').modal('hide');
}
function submitMain(status){
    ue.sync();
    var type = $('#mainForm select[name=type]').val();
    if(type != 3 && $('input[name=startDate]').val() == ''){
        option = {title:'出错啦',content:'请填写开始日期',buttons:[{type:'close',text:'知道了'}]};
        beautyAlert(option);
        $('#startDate').parents('.control-group').addClass('error');
        return;
    }
    if(type == 2 && $('input[name=endDate]').val() == ''){
        option = {title:'出错啦',content:'请填写结束日期',buttons:[{type:'close',text:'知道了'}]};
        beautyAlert(option);
        $('#endDate').parents('.control-group').addClass('error');
        return;
    }
    if($('#mainForm input[name=title]').val() == ''){
        option = {title:'出错啦',content:'请填标题',buttons:[{type:'close',text:'知道了'}]};
        beautyAlert(option);
        $('#mainForm input[name=title]').parents('.control-group').addClass('error');
        return;
    }
    if(type != 2 && ue.getContentLength(true) == 0){
        option = {title:'出错啦',content:'内容不能为空哦',buttons:[{type:'close',text:'知道了'}]};
        beautyAlert(option);
        return;
    }
    $('#mainForm').mask('正在保存中……');
    page = $('.pagination .active').text();
    //param = $('#mainForm').serialize() + '&' + window.asset + '&status=' + status + '&p=' + page;
    param = {
        id : $('#mainForm input[name=id]').val(),
        type: $('#mainForm select[name=type]').val(),
        startDate: $('#mainForm input[name=startDate]').val(),
        endDate: $('#mainForm input[name=endDate]').val(),
        title: $('#mainForm input[name=title]').val(),
        text: ue.getContent(),
        status: status,
        p: page
    };
    param.url = asset.media;
    param.caption = asset.caption;
    param.credit = asset.credit;
    $.post('/admin/index.php?m=Index&a=Save', param, function(data){
        if(data.status == true){
            window.timelineList = data.data.list;
            genList(window.timelineList);
            $('.pagination ul').html(data.data.page);
            resetMain();
        }else{
            alert('请求出错');
        }
        $('#mainForm').unmask();
        location.href = '#list';
    }, 'json');
}
function resetMain(){
    $('#mainForm')[0].reset();
    $('#mainForm input[name=id]').val(0);
    $('#mainForm select[name=type]').trigger('change');
    ue.setContent('');
    delAsset();
}

function genList(list){
    for(var x in list){
        type = '';
        switch(list[x]['type']){
            case '1':
                type = '普通';
                break;
            case '2':
                type = '大事记';
                break;
            case '3':
                type = '头条';
                break;
        }
        if(list[x]['status'] == 0){
            type += '(草稿)';
            list[x]['status'] = false;
        }
        list[x]['typeStr'] = type;
    }
    var tpl = new t("{{@list}}<tr id='tr_{{%_val.id}}'><td>{{=_val.typeStr}}</td><td>{{=_val.startDate}}</td><td>{{=_val.endDate}}</td><td>{{=_val.headline}}</td><td>{{_val.status}}<a class='btn temp'>设为草稿</a>{{:_val.status}}<a class='btn noTemp'>设为正式</a>{{/_val.status}}&nbsp;<a class='btn edit'>编辑</a>&nbsp;<a class='btn btn-danger del'>删除</a></td></tr>{{/@list}}");
    var html = tpl.render({list:list});
    $('#list tbody').html(html);
}
function getUrlParam(url, name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = url.match(reg);  //匹配目标参数
    if (r!=null) return unescape(r[2]); return null; //返回参数值
}
function searchList(id){
    for(var x in window.timelineList){
        if(timelineList[x]['id'] == id){
            return x;
        }
    }
    return -1;
}
function htmlspecialchars_decode(string) {
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    string = string.replace(/&#0*39;/g, "'");
    string = string.replace(/&quot;/g, '"');
    string = string.replace(/&amp;/g, '&');
    return string;
}
function switchTemp(id, status){
    $('#list').mask('给力加载中……');
    page = $('.pagination .active').text();
    $.post('/admin/index.php?m=Index&a=SwitchTemp', {id:id,status:status,p:page}, function(data){
        if(data.status == true){
            window.timelineList = data.data.list;
            genList(window.timelineList);
            $('.pagination ul').html(data.data.page);
        }else{
            alert('请求出错');
        }
        $('#list').unmask();
    }, 'json');
}
</script>
<?php
View::tplInclude('Public/footer');
?>
